import { Modal, Card, Breadcrumb, Form, Button, DatePicker, Radio, Table, Tag, Space, message } from 'antd'
import { Link, useHistory } from 'react-router-dom'
import style from './index.module.scss'
// 导入枚举
import { ArticleStatus } from '@/api/constants'
// 加载失败的图片
import errImg from '@/assets/error.png'
// antd的图标
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
// 导入api
import { getArticles, delArticle } from '@/api'
// 导入hook
import { useEffect, useState } from 'react'
// 导入抽取的频道组件
import Channels from '@/components/Channels'
// 解构获取到内部的组件
const { RangePicker } = DatePicker
const { confirm } = Modal

// 函数组件
function Article() {
  // 文章数据的hook
  const [articles, setArticles] = useState([
    {
      comment_count: 0,
      cover: { type: 0, images: [] },
      id: '8218',
      like_count: 0,
      pubdate: '2019-03-11 09:00:00',
      read_count: 0,
      status: 2,
      title: 'wkwebview离线化加载h5资源解决方案',
    },
    {
      comment_count: 0,
      cover: { type: 1, images: ['http://geek.itheima.net/resources/images/9.jpg'] },
      id: '8217',
      like_count: 0,
      pubdate: '2019-03-11 09:00:00',
      read_count: 0,
      status: 2,
      title: '深入理解Java虚拟机06--虚拟机字节码执行引擎',
    },
  ])
  // 总条数的hook
  const [total, setTotal] = useState(0)
  // form的hook
  const [form] = Form.useForm()
  // history的hook
  const history = useHistory()

  // 处理表单数据的方法
  const formatForm = (formData) => {
    const { date, status, channel_id } = formData
    const params = {}
    status != -1 && (params.status = status)
    channel_id != 0 && (params.channel_id = channel_id)
    date && (params.begin_pubdate = date[0].format('YYYY-MM-DD hh:mm:ss'))
    date && (params.end_pubdate = date[1].format('YYYY-MM-DD hh:mm:ss'))
    // 返回出去
    return params
  }

  // 获取文章的数据
  const fetchArticle = async (params) => {
    const res = await getArticles(params)
    // console.log('res:', res)
    setArticles(res.data.results)
    setTotal(res.data.total_count)
  }

  const onFinish = (value) => {
    // 判断是否需要 生成提交对象
    // 调用接口 获取数据 保存数据 更新页面
    fetchArticle(formatForm(value))
  }

  // 分页组件的回调函数
  // page 页码
  // per_page 也容量
  const onChange = (page, per_page) => {
    // form的数据
    const formData = form.getFieldsValue(true)
    const params = formatForm(formData)
    // 把页码 和 格式化之后的form数据 合并到一起
    fetchArticle({ page, per_page, ...params })
  }

  // 弹出删除确认框
  const showDel = (id) => {
    confirm({
      title: '提示',
      icon: <DeleteOutlined />,
      content: '确认删除数据？',
      async onOk() {
        console.log('确认')
        // 有id 删除
        // console.log('id:', id)
        await delArticle(id)
        // 提示用户
        message.success('删除成功')
        // 重新获取数据
        fetchArticle()
      },
      onCancel() {
        console.log('取消')
      },
    })
  }

  // 获取数据
  useEffect(() => {
    // 获取文章数据
    fetchArticle()
  }, [])

  // table的列设置
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      key: 'cover',
      render(text) {
        if (text.type === 0) {
          return <img className='cover' src={errImg} alt='' />
        } else {
          return <img className='cover' src={text.images[0]} alt='' />
        }
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render(status) {
        const res = ArticleStatus.find((v) => v.id === status)
        return <Tag color={res.color}>{res.name}</Tag>
      },
    },
    {
      title: '发布时间',
      key: 'pubdate',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
      key: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
      key: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
      key: 'like_count',
    },
    {
      title: '操作',
      key: 'action',
      // 没有给 dataIndex 默认第一个参数就是所有的数据
      // 给了dataIndex，可以通过第二个参数获取所以
      render(action) {
        // console.log('action:', action)
        return (
          <Space>
            <Button
              onClick={() => {
                history.push('/home/publish/' + action.id)
              }}
              icon={<EditOutlined />}
              type='primary'
              shape='circle'
            ></Button>
            <Button onClick={() => showDel(action.id)} danger icon={<DeleteOutlined />} type='primary' shape='circle'></Button>
          </Space>
        )
      },
    },
  ]

  return (
    <div className={style.article}>
      {/* 头部卡片 */}
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to='/home'>首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>内容管理</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form form={form} wrapperCol={{ span: 8 }} name='basic' initialValues={{ status: -1, channel_id: 0 }} onFinish={onFinish} autoComplete='off'>
          <Form.Item name='status' label='状态'>
            <Radio.Group>
              {ArticleStatus.map((v) => {
                return (
                  <Radio key={v.id} value={v.id}>
                    {v.name}
                  </Radio>
                )
              })}
            </Radio.Group>
          </Form.Item>
          <Form.Item label='频道' name='channel_id'>
            {/* form会自动把value 和 onChange传递进去 */}
            <Channels></Channels>
          </Form.Item>

          <Form.Item label='日期' name='date'>
            <RangePicker />
          </Form.Item>

          <Form.Item wrapperCol={{ span: 8 }}>
            <Button type='primary' htmlType='submit'>
              筛选
            </Button>
          </Form.Item>
        </Form>
      </Card>
      {/* 底部卡片 */}
      <Card title={`根据筛选条件共查询到${total}条结果`}>
        {/*  es6的简写  */}
        <Table pagination={{ total, onChange }} rowKey='id' columns={columns} dataSource={articles} />
      </Card>
    </div>
  )
}
export default Article
